using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Transactions;

namespace FeedGatheringService
{
    partial class FeedGatheringService : ServiceBase
    {
        protected System.Timers.Timer feedGathererTimer; 

        public FeedGatheringService()
        {
            InitializeComponent();
            feedGathererTimer = new System.Timers.Timer();
            feedGathererTimer.Interval = 30000; //900000;
            feedGathererTimer.Enabled = false;
            feedGathererTimer.Elapsed += new ElapsedEventHandler(feedGathererTimer_Elapsed);
        }

        private void feedGathererTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            WriteToLog("Feed Gatherer Service is Running");

            // Get the list of feeds that we will poll
            List<Feed> feedList = Feed.GetList();

            foreach (Feed feed in feedList)
            {
                WriteToLog(string.Format("Adding posts from feed: \"{0}\"", feed.Title));
                
                // Go get the posts for each feed
                List<Post> postList = Post.GetNewRssPostsFromUrl(feed);

                using (TransactionScope ts = new TransactionScope())
                {
                    // if the Feed and its Guid changed, update the feed
                    if (feed.LastPostGuidNameChanged)
                        feed.Update();

                    // If it has posts, add them
                    if (postList.Count > 0)
                        foreach (Post post in postList)
                            post.Add();

                    ts.Complete();
                }
            }
            WriteToLog(string.Format("Successfully added the new posts from {0} feeds", feedList.Count));
        }

        protected override void OnStart(string[] args)
        {
            feedGathererTimer.Enabled = true;
            WriteToLog("Feed Gatherer Service Started"); 
        }

        protected override void OnStop()
        {
            feedGathererTimer.Enabled = false;
            WriteToLog("Feed Gatherer Service Stopped");
        }

        private void WriteToLog(string msg)
        {
            EventLog.WriteEntry("Feed Gatherer Service", msg, EventLogEntryType.Information);
        }

    }
}
